.addEventListener('DOMContentLoaded', function() {
    // 初始化页面
    initNavigation();
    loadDashboardData();
    setupEventListeners();
    
    // 每10秒刷新一次数据
    setInterval(loadDashboardData, 10000);
});

function initNavigation() {
    const navItems = document.querySelectorAll('.sidebar li');
    const contentSections = document.querySelectorAll('.content-section');
    
    navItems.forEach(item => {
        item.addEventListener('click', function() {
            navItems.forEach(nav => nav.classList.remove('active'));
            contentSections.forEach(section => section.classList.remove('active'));
            
            this.classList.add('active');
            const targetId = this.querySelector('a').getAttribute('href').substring(1);
            document.getElementById(targetId).classList.add('active');
        });
    });
}

async function loadDashboardData() {
    try {
        const response = await fetch('/api/dashboard');
        const data = await response.json();
        
        document.getElementById('water-level').textContent = `${data.waterLevel}m`;
        document.getElementById('flow-rate').textContent = `${data.flowRate}m³/s`;
        document.getElementById('weather-info').textContent = data.weather;
    } catch (error) {
        console.error('加载数据失败:', error);
    }
}

function setupEventListeners() {
    document.getElementById('logout').addEventListener('click', function() {
        fetch('/api/logout', { method: 'POST' })
            .then(() => window.location.href = '/login.html')
            .catch(err => console.error('退出失败:', err));
    });
}

